package com.zheng.coderepo.algorithm;

import org.junit.Assert;
import org.junit.Test;

/**
 * 找第 n 个数(字符串表示)，规则则是对于连续字符串，表示为重复次数+数本身。
 * 1) 1即是11，表示1个1.
 * 2) 11即是21，表示2个1.
 * 3) 21即是1211，表示1个2，1个1。
 * 4) 1211即是111221,表示1个1,1个2,2个1。
 * 经过4次后结果是1211。
 * Created by zcz on 2018/5/22.
 */
public class NumberCountAndSay {

    public String countAndSay01(int n) {
        if (n <= 0) {
            return "";
        } else if (n == 1) {
            return "1";
        }
        String result = "1";
        for (int i = 2; i <= n; i++) {
            StringBuilder builder = new StringBuilder();
            char[] chars = result.toCharArray();
            char temp = chars[0];
            int count = 1;
            for (int k = 1; k < chars.length; k++) {
                if (temp == chars[k]) {
                    count++;
                } else {
                    builder.append(count).append(temp);
                    temp = chars[k];
                    count = 1;
                }
            }
            builder.append(count).append(temp);
            result = builder.toString();
            builder.delete(0, builder.length() - 1);
        }
        return result;
    }

    @Test
    public void testCountAndSay01() {
        Assert.assertEquals("1", countAndSay01(1));
        Assert.assertEquals("11", countAndSay01(2));
        Assert.assertEquals("21", countAndSay01(3));
        Assert.assertEquals("1211", countAndSay01(4));
        Assert.assertEquals("111221", countAndSay01(5));
        Assert.assertEquals("312211", countAndSay01(6));
        Assert.assertEquals("13112221", countAndSay01(7));
    }
}
